<template>
  <div class="tree-main-body">
    <!-- 左侧 Tabs -->
    <div class="left-box">
      <a-tabs
        v-model:activeKey="tabKey"
        centered
        :tabBarGutter="55"
      >
        <a-tab-pane key="1" tab="分类">
          <div class="float-left">
            <TreeCategory
              :selected="category_ids"
              text="分类"
              @update="onCategoryUpdate"
            />
          </div>
        </a-tab-pane>
        <a-tab-pane key="2" tab="部门">
          <div class="float-left">
            <TreeDepartment
              :selected="dep_ids"
              :showNum="false"
              :refresh="refresh"
              text="部门"
              @update="onDepartmentUpdate"
            />
          </div>
        </a-tab-pane>
      </a-tabs>
    </div>

    <!-- 右侧 -->
    <div class="right-box">
      <div class="d-flex playedu-main-title float-left mb-24">
        线上课 | {{ tabKey === "1" ? selLabel : selDepLabel }}
      </div>

      <!-- 顶部搜索与按钮 -->
      <div class="float-left j-b-flex mb-24">
        <div class="d-flex">
          <PerButton
            type="primary"
            text="新建课程"
            class="mr-16"
            :icon="h(PlusOutlined)"
            p="course"
            @click="createVisible = true"
          />
        </div>
        <div class="d-flex">
          <div class="d-flex mr-24">
            <a-typography-text>课程名称：</a-typography-text>
            <a-input
              v-model:value="title"
              allowClear
              style="width:160px"
              placeholder="请输入名称关键字"
              @change="handleTitleChange"
            />
          </div>
          <div class="d-flex">
            <a-button class="mr-16" @click="resetList">重 置</a-button>
            <a-button type="primary" @click="queryList">查 询</a-button>
          </div>
        </div>
      </div>

      <!-- 表格 -->
      <a-table
        :columns="columns"
        :data-source="list"
        :loading="loading"
        :pagination="paginationProps"
        rowKey="id"
      />

      <!-- 弹窗 -->
      <CourseCreate
        :cateIds="tabKey === '1' ? category_ids : []"
        :open="createVisible"
        @cancel="onCreateCancel"
      />
      <CourseUpdate
        :id="cid"
        :open="updateVisible"
        @cancel="onUpdateCancel"
      />
      <CourseAttachmentUpdate
        :id="cid"
        :open="updateHourVisible"
        @cancel="onHourUpdateCancel"
      />
      <CourseHourUpdate
        :id="cid"
        :open="updateAttachmentVisible"
        @cancel="onAttachmentUpdateCancel"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, h, computed, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import {
  Modal,
  message,
  Image,
  Space,
  Dropdown,
  Button as AButton,
  Menu
} from "ant-design-vue";
import { PlusOutlined, DownOutlined, ExclamationCircleFilled } from "@ant-design/icons-vue";
import { course } from "../../api";
import { dateFormat } from "../../utils";
import TreeDepartment from "@/components/Common/tree-department.vue";
import TreeCategory from "@/components/Common/tree-category.vue";
import PerButton from "@/components/Common/permission-button.vue";
import CourseCreate from "./create.vue";
import CourseUpdate from "./update.vue";
import CourseHourUpdate from "./hour-update.vue";
import CourseAttachmentUpdate from "./attachments-update.vue";
import defaultThumb1 from "@/assets/thumb/thumb1.png";
import defaultThumb2 from "@/assets/thumb/thumb2.png";
import defaultThumb3 from "@/assets/thumb/thumb3.png";

const route = useRoute();
const router = useRouter();

const page = ref(Number(route.query.page) || 1);
const size = ref(Number(route.query.size) || 10);
const title = ref<string>((route.query.title as string) || "");
const tabKey = ref(route.query.did ? "2" : "1");

const list = ref<any[]>([]);
const total = ref(0);
const loading = ref(false);
const refresh = ref(false);

const category_ids = ref<number[]>([]);
const dep_ids = ref<number[]>([]);
const selLabel = ref("全部分类");
const selDepLabel = ref("全部部门");

const course_category_ids = ref<any>({});
const course_dep_ids = ref<any>({});
const categories = ref<any>({});
const departments = ref<any>({});
const adminUsers = ref<any>({});
const resourceUrl = ref<any>({});

const createVisible = ref(false);
const updateVisible = ref(false);
const updateHourVisible = ref(false);
const updateAttachmentVisible = ref(false);
const cid = ref(0);

onMounted(() => {
  getList();
});

// 修复：创建菜单项的正确方式
const createMenuItems = (record: any) => {
  return [
    {
      key: "1",
      label: '编辑',
      onClick: () => {
        cid.value = Number(record.id);
        updateVisible.value = true;
      }
    },
    {
      key: "2",
      label: '课时',
      onClick: () => {
        cid.value = Number(record.id);
        updateHourVisible.value = true;
      }
    },
    {
      key: "3",
      label: '课件',
      onClick: () => {
        cid.value = Number(record.id);
        updateAttachmentVisible.value = true;
      }
    },
    {
      key: "4",
      label: '删除',
      onClick: () => delItem(record.id)
    },
  ];
};

// 修复：创建下拉菜单的渲染函数
const renderDropdownMenu = (record: any) => {
  const menuItems = createMenuItems(record);
  
  return h(Menu, {
    items: menuItems.map(item => ({
      key: item.key,
      label: h('span', {
        onClick: item.onClick,
        style: { 
          display: 'block', 
          padding: '4px 12px',
          cursor: 'pointer'
        }
      }, item.label)
    }))
  });
};

// 表格列配置
const columns = computed(() => [
  {
    title: "课程名称",
    width: 350,
    customRender: ({ record }: { record: any }) => {
      const thumbSrc = getThumb(record.thumb);
      return h('div', { class: 'd-flex', style: 'align-items: center;' }, [
        h(Image, {
          preview: false,
          width: 80,
          height: 60,
          style: { borderRadius: '6px' },
          src: thumbSrc
        }),
        h('span', { class: 'ml-8' }, record.title)
      ]);
    },
  },
  {
    title: "课程分类",
    customRender: ({ record }: { record: any }) => {
      const id = record.id;
      const categoryIds = course_category_ids.value[id];
      
      if (!categoryIds || !Array.isArray(categoryIds)) {
        return h('span', '-');
      }
      
      return h('div', { class: 'float-left' }, 
        categoryIds.map((item: any, index: number) => {
          const categoryName = categories.value[item] || '未知分类';
          return h('span', { key: index },
            index === categoryIds.length - 1
              ? categoryName
              : categoryName + "、"
          );
        })
      );
    },
  },
  {
    title: "指派部门",
    customRender: ({ record }: { record: any }) => {
      const id = record.id;
      const depIds = course_dep_ids.value[id];
      
      if (!depIds || !Array.isArray(depIds)) {
        return h('span', '全部部门');
      }
      
      return h('div', { class: 'float-left' }, 
        depIds.map((item: any, index: number) => {
          const depName = departments.value[item] || '未知部门';
          return h('span', { key: index },
            index === depIds.length - 1
              ? depName
              : depName + "、"
          );
        })
      );
    },
  },
  {
    title: "必修/选修",
    dataIndex: "is_required",
    customRender: ({ text }: { text: number }) => {
      return h('span', text === 1 ? "必修课" : "选修课");
    },
  },
  {
    title: "创建人",
    dataIndex: "admin_id",
    customRender: ({ text }: { text: number }) => {
      const adminName = adminUsers.value[text];
      return h('span', adminName || "-");
    },
  },
  {
    title: "上架时间",
    dataIndex: "sort_at",
    customRender: ({ text }: { text: string }) => {
      return h('span', dateFormat(text));
    },
  },
  {
    title: "操作",
    key: "action",
    fixed: "right",
    width: 160,
    customRender: ({ record }: { record: any }) => {
      return h(Space, { size: "small" }, [
        h(PerButton, {
          type: "link",
          text: "学员",
          class: "b-link c-red",
          p: "course",
          onClick: () => {
            cid.value = Number(record.id);
            router.push("/course/user/" + Number(record.id) + "?title=" + record.title);
          }
        }),
        h(Dropdown, {
          trigger: ['click'],
          overlay: renderDropdownMenu(record)
        }, {
          default: () => h(AButton, {
            type: "link",
            class: "b-link c-red"
          }, [
            h(Space, { size: "small", align: "center" }, [
              "更多",
              h(DownOutlined)
            ])
          ])
        })
      ]);
    },
  },
]);

// 监听数据变化
watch([page, size, refresh], () => {
  getList();
});

watch(tabKey, () => {
  page.value = 1;
  getList();
});

watch(category_ids, () => {
  page.value = 1;
  getList();
});

watch(dep_ids, () => {
  page.value = 1;
  getList();
});

const getList = async () => {
  loading.value = true;
  
  let categoryIds = "";
  let depIds = "";
  
  if (tabKey.value === "1") {
    categoryIds = category_ids.value.join(",");
  } else {
    depIds = dep_ids.value.join(",");
  }
  
  try {
    const res: any = await course.courseList(
      page.value,
      size.value,
      "",
      "",
      title.value,
      depIds,
      categoryIds
    );
    
    if (res && res.data) {
      total.value = res.data.total;
      list.value = res.data.data || [];
      course_category_ids.value = res.data.course_category_ids || {};
      course_dep_ids.value = res.data.course_dep_ids || {};
      categories.value = res.data.categories || {};
      departments.value = res.data.departments || {};
      adminUsers.value = res.data.admin_users || {};
      resourceUrl.value = res.data.resource_url || {};
    } else {
      list.value = [];
      total.value = 0;
    }
  } catch (err) {
    console.error("获取课程列表错误:", err);
    list.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

const resetList = () => {
  page.value = 1;
  size.value = 10;
  title.value = "";
  list.value = [];
  refresh.value = !refresh.value;
};

const queryList = () => {
  page.value = 1;
  refresh.value = !refresh.value;
};

const handleTitleChange = (e: Event) => {
  title.value = (e.target as HTMLInputElement).value;
};

const paginationProps = computed(() => ({
  current: page.value,
  pageSize: size.value,
  total: total.value,
  showSizeChanger: true,
  onChange: (p: number, s: number) => {
    page.value = p;
    size.value = s;
  },
}));

const getThumb = (thumb: number | string) => {
  if (thumb === -1) return defaultThumb1;
  if (thumb === -2) return defaultThumb2;
  if (thumb === -3) return defaultThumb3;
  return resourceUrl.value[thumb] || defaultThumb1;
};

// 事件方法
const onCategoryUpdate = (keys: any, titleText: any) => {
  page.value = 1;
  category_ids.value = keys;
  selLabel.value = typeof titleText === "string" ? titleText : titleText.props.children[0];
  getList();
};

const onDepartmentUpdate = (keys: any, titleText: any) => {
  page.value = 1;
  dep_ids.value = keys;
  selDepLabel.value = titleText;
  getList();
};

const delItem = (id: number) => {
  if (!id) return;
  Modal.confirm({
    title: "操作确认",
    icon: h(ExclamationCircleFilled),
    content: "确认删除此课程？",
    centered: true,
    okText: "确认",
    cancelText: "取消",
    onOk: async () => {
      try {
        await course.destroyCourse(id);
        message.success("删除成功");
        getList();
      } catch (error) {
        message.error("删除失败");
      }
    },
  });
};

// 弹窗关闭
const onCreateCancel = () => {
  createVisible.value = false;
  getList();
};

const onUpdateCancel = () => {
  updateVisible.value = false;
  getList();
};

const onHourUpdateCancel = () => {
  updateHourVisible.value = false;
  getList();
};

const onAttachmentUpdateCancel = () => {
  updateAttachmentVisible.value = false;
  getList();
};
</script>

<style scoped>
</style>